package tclp.listener;

import java.io.File;
import org.jnativehook.keyboard.NativeKeyEvent;
import org.jnativehook.keyboard.NativeKeyListener;
import tclp.capture.CaptureThread;
import tclp.gui.GUIController;

/**
 *
 * @author Absatz Leoš
 */
public class ActivationKeyListener implements NativeKeyListener {

    private GUIController controller;
    private NativeKeyEvent last;
    private CaptureThread captureThread;
    private boolean captureRunning = false;

    public ActivationKeyListener(GUIController controller) {
        this.controller = controller;
    }

    public void keyPressed(NativeKeyEvent nke) {
        last = nke;

        // toggle capture
        NativeKeyEvent activationKey = controller.getActivationKey();
        if ((nke.getModifiers() == activationKey.getModifiers()) && (nke.getKeyCode() == activationKey.getKeyCode())) {
            captureRunning = !captureRunning;
            controller.getMainPanel().setStatus(captureRunning);
        }

        if (captureRunning) {
            if (captureThread == null) {
                captureThread = new CaptureThread(controller.getScreenCoords(), controller.getTrainingImages(),
                        controller.getFrapsPath(), controller.getOutputFile());
            }
            if (!captureThread.isRunning()) {
                // delete all screenshots in the fraps directory
                File frapsScreenshotsPath = new File(controller.getFrapsPath());
                File[] files = frapsScreenshotsPath.listFiles();
                if (files != null) {
                    for (File file : files) {
                        if (file.isFile()) {
                            file.delete();
                        }
                    }
                }

                captureThread.start();
            }

//      System.out.println("Pushed " + nke.paramString() + ", keyCode " + nke.getKeyCode() + ", mod "
//          + nke.getModifiers());
        } else {
            captureThread.setRunning(false);
            try {
                captureThread.join();
            } catch (InterruptedException ex) {
                System.out.println(ex);
                System.exit(1);
            }
            captureThread = null;
        }
    }

    public void keyReleased(NativeKeyEvent nke) {
        // noop
    }

    public NativeKeyEvent getLastKeyPressed() {
        return last;
    }
}
